package com.sl.au.service.impl;

import java.util.*;

import com.sl.au.entity.*;
import com.sl.au.repository.AfterSaleActiveRepository;
import com.sl.au.repository.ChanceDeliveryRepository;
import com.sl.au.repository.ContractRepository;
import com.sl.au.repository.CustomerRepository;
import com.sl.au.service.AfterSaleActiveService;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.comparators.ComparatorChain;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sl.au.repository.TaskRepository;
import com.sl.au.service.IndexService;
import com.sl.au.service.SectionService;
import com.sl.utils.DataConverter;

import org.springframework.util.StringUtils;

@Service("IndexService")
@Transactional
public class IndexServiceImpl extends BaseServiceImpl implements IndexService {
	@Autowired
	TaskRepository taskRepository;
	@Autowired
	AfterSaleActiveRepository afterSaleActiveRepository;
	@Autowired
	ContractRepository contractRepository;
	@Autowired
	SectionService sectionService;
	@Autowired
	ChanceDeliveryRepository chanceDeliveryRepository;
	
	@Autowired
	CustomerRepository customerRepository;
	
	@Override
	public TaskRepository getRepository() {

		return this.taskRepository;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ChanceInfo> getChanceDealPage(User user, String role) {
		// TODO Auto-generated method stub
		List<ChanceInfo> chanceInfos = new ArrayList<ChanceInfo>();
		Pageable pageable = new PageRequest(0, 5, Sort.Direction.DESC, "createTime");
		// 获取信息跟踪待处理信息
		List<ChanceManagerDelivery> chanceManagerDeliverys = new ArrayList<ChanceManagerDelivery>();
		Page<ChanceManagerDelivery> chanceTrance = null;
		String sectionId="";
		Section s=sectionService.getRepository().findByChief(user);
		if(s!=null){
			sectionId=s.getId();
		}
		chanceTrance = taskRepository.getChanceTrances(user.getId(), pageable);
		chanceManagerDeliverys = chanceTrance.getContent();
		for (ChanceManagerDelivery c : chanceManagerDeliverys) {
			ChanceInfo chanceInfo = new ChanceInfo();
			chanceInfo.setChanceId(c.getSaleChance().getId());
			chanceInfo.setChanceName(c.getSaleChance().getName());
			chanceInfo.setTaskDate(c.getCreateTime());
			chanceInfo.setChanceType(1);
			chanceInfos.add(chanceInfo);
		}
		if (role.indexOf("经理") != -1 || role.indexOf("管理员") != -1) {
			// 获取信息分配（经理）待处理信息
			List<ChanceDelivery> chanceDeliverys = new ArrayList<ChanceDelivery>();
			Page<ChanceDelivery> chanceDelivery = null;
			chanceDelivery = taskRepository.getChanceManagerDeliverys(user.getSaleArea().getId(), pageable);
			chanceDeliverys = chanceDelivery.getContent();
			for (ChanceDelivery c : chanceDeliverys) {
				ChanceInfo chanceInfo = new ChanceInfo();
				chanceInfo.setChanceId(c.getSaleChance().getId());
				chanceInfo.setChanceName(c.getSaleChance().getName());
				chanceInfo.setTaskDate(c.getCreateTime());
				chanceInfo.setChanceType(2);
				chanceInfos.add(chanceInfo);
			}
		}
		if (role.indexOf("处长") != -1 || role.indexOf("管理员") != -1) {
			
			// 获取信息分配（处长）待处理信息
			List<ChanceDeliveryTemp> chanceDeliveryTemps = new ArrayList<ChanceDeliveryTemp>();
			Page<ChanceDeliveryTemp> chanceDeliveryTemp = null;
			chanceDeliveryTemp = taskRepository.getChanceDeliverys(user.getSaleArea().getSuperior(), pageable);
			chanceDeliveryTemps = chanceDeliveryTemp.getContent();
			for (ChanceDeliveryTemp c : chanceDeliveryTemps) {
				ChanceInfo chanceInfo = new ChanceInfo();
				chanceInfo.setChanceId(c.getSaleChance().getId());
				chanceInfo.setChanceName(c.getSaleChance().getName());
				chanceInfo.setTaskDate(c.getCreateTime());
				chanceInfo.setChanceType(3);
				chanceInfos.add(chanceInfo);
			}
		}
		if (role.indexOf("科长") != -1 || role.indexOf("管理员") != -1) {
			// 获取信息分配（科长）待处理信息
			List<ChanceDeliveryTemp> chanceDeliveryTemps = new ArrayList<ChanceDeliveryTemp>();
			Page<ChanceDeliveryTemp> chanceDeliveryTemp = null;
			chanceDeliveryTemp = taskRepository.getSectionChanceDeliverys(sectionId, pageable);
			chanceDeliveryTemps = chanceDeliveryTemp.getContent();
			for (ChanceDeliveryTemp c : chanceDeliveryTemps) {
				ChanceInfo chanceInfo = new ChanceInfo();
				chanceInfo.setChanceId(c.getSaleChance().getId());
				chanceInfo.setChanceName(c.getSaleChance().getName());
				chanceInfo.setTaskDate(c.getCreateTime());
				chanceInfo.setChanceType(3);
				chanceInfos.add(chanceInfo);
			}
		}
		// 把所有的待处理信息根据时间排序
		if (chanceInfos != null) {
			ComparatorChain chain = new ComparatorChain();
			chain.addComparator(new BeanComparator("taskDate"), true);
			Collections.sort(chanceInfos, chain);
		}

		return chanceInfos;
	}

	@Override
	public List<Task> getMyTask(int start, int length, String userId, String roleId) {
		Page<Task> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
		pages = taskRepository.getMyTask(userId, roleId, pageable);
		return pages.getContent();
	}

	public void getAafterSale() {
		String rolename = "售后内勤";
		Role r = taskRepository.findByName(rolename);
		String name = "维护超期";
		List<ContractVo> contracts = this.getContract();
		for (ContractVo ContractVo : contracts) {
			String taskId = ContractVo.getContractId();
			Task t1 = taskRepository.findByUndoTaskIdAndName(taskId, name);
			if (t1 == null) {
				Task t = new Task();
				t.setTransactorId(r.getId());
				t.setContent("/ui/aftersaleactive");
				t.setName("维护超期");
				t.setUndoTaskId(ContractVo.getContractId());
				taskRepository.save(t);
			}
		}
	}

	public List<ContractVo> getContract() {
		List<Contract> contracts = contractRepository.findAll();
		List<ContractVo> contractVos = new ArrayList<>();
		for (Contract contract : contracts) {
			ContractVo contractVo = new ContractVo();
			contractVo = setContractVoData(contract);
			Date servicingTime = new Date();// 最早维护时间
			contractVo.setServicingTime(servicingTime);
			List<MaintainItemDevice> mids = this.afterSaleActiveRepository
					.getMaintainPlansByContractID(contract.getId());
			String state = "正常";
			if (mids.size() > 0) {
				if (mids.get(0).getStartDate() != null) {
					Date startDate = mids.get(0).getStartDate();
					int day = mids.get(0).getMaintainPeriod();// 最早的计划的维护周期
					long time = startDate.getTime(); // 得到出厂日期的毫秒数
					long dayTime = 24 * 60 * 60 * 1000; // 一天的时间转换成毫秒数
					time += day * dayTime; // 相加得到新的毫秒数
					startDate = new Date(time); // 将毫秒数转换成日期
					contractVo.setServicingTime(startDate);
					long nowTime = servicingTime.getTime();
					if (time < nowTime) {
						state = "已超期";
					}
				}
			}
			contractVo.setState(state);
			if (contractVo.getState() == "已超期") {
				contractVos.add(contractVo);
			}
		}
		return contractVos;
	}

	private ContractVo setContractVoData(Contract contract) {
		ContractVo contractVo = new ContractVo();
		if (StringUtils.hasText(contract.getId())) {
			contractVo.setContractId(contract.getId());
		}
		if (contract.getCreateTime() != null) {
			contractVo.setCreateTime(contract.getCreateTime());
		}
		if (StringUtils.hasText(contract.getSupplierCode())) {
			contractVo.setSupplierCode(contract.getSupplierCode());
		}
		if (StringUtils.hasText(contract.getDemanderCode())) {
			contractVo.setDemanderCode(contract.getDemanderCode());
		}
		if (StringUtils.hasText(contract.getContractType())) {
			contractVo.setContractType(contract.getContractType());
		}
		contractVo.setTotalSum(contract.getTotalSum());
		if (contract.getSignedDate() != null) {
			contractVo.setSignedDate(contract.getSignedDate());
		}
		if (contract.getScheduleDate() != null) {
			contractVo.setScheduleDate(contract.getScheduleDate());
		}
		if (contract.getDeliveryDate() != null) {
			contractVo.setDeliveryDate(contract.getDeliveryDate());
		}
		if (StringUtils.hasText(contract.getStop())) {
			contractVo.setStop(contract.getStop());
		}
		contractVo.setFreightCharge(contract.getFreightCharge());
		if (StringUtils.hasText(contract.getProjectName())) {
			contractVo.setProjectName(contract.getProjectName());
		}
		if (StringUtils.hasText(contract.getPayType())) {
			contractVo.setPayType(contract.getPayType());
		}
		if (StringUtils.hasText(contract.getGuaranteePeriod())) {
			contractVo.setGuaranteePeriod(contract.getGuaranteePeriod());
		}
		if (StringUtils.hasText(contract.getBreakDuty())) {
			contractVo.setBreakDuty(contract.getBreakDuty());
		}
		if (StringUtils.hasText(contract.getOrderUnit())) {
			contractVo.setOrderUnit(contract.getOrderUnit());
		}
		if (StringUtils.hasText(contract.getOrderDelegate())) {
			contractVo.setOrderDelegate(contract.getOrderDelegate());
		}
		if (StringUtils.hasText(contract.getOrderPhone())) {
			contractVo.setOrderPhone(contract.getOrderPhone());
		}
		if (StringUtils.hasText(contract.getIndustryInfo())) {
			contractVo.setIndustryInfo(contract.getIndustryInfo());
		}
		if (StringUtils.hasText(contract.getOrderAddress())) {
			contractVo.setOrderAddress(contract.getOrderAddress());
		}
		contractVo.setOrderZip(contract.getOrderZip());
		if (StringUtils.hasText(contract.getOrderArea())) {
			contractVo.setOrderArea(contract.getOrderArea());
		}
		if (StringUtils.hasText(contract.getPostUnit())) {
			contractVo.setPostUnit(contract.getPostUnit());
		}
		if (StringUtils.hasText(contract.getPostDelegate())) {
			contractVo.setPostDelegate(contract.getPostDelegate());
		}
		if (StringUtils.hasText(contract.getPostPhone())) {
			contractVo.setPostPhone(contract.getPostPhone());
		}
		if (StringUtils.hasText(contract.getPostAddress())) {
			contractVo.setPostAddress(contract.getPostAddress());
		}
		contractVo.setPostZip(contract.getPostZip());
		if (StringUtils.hasText(contract.getDutyArea())) {
			contractVo.setDutyArea(contract.getDutyArea());
		}
		if (StringUtils.hasText(contract.getDutyOfficer())) {
			contractVo.setDutyOfficer(contract.getDutyOfficer());
		}
		if (StringUtils.hasText(contract.getSouthNorthArea())) {
			contractVo.setSouthNorthArea(contract.getSouthNorthArea());
		}
		if (StringUtils.hasText(contract.getBelongArea())) {
			contractVo.setBelongArea(contract.getBelongArea());
		}
		if (StringUtils.hasText(contract.getCheckKind())) {
			contractVo.setCheckKind(contract.getCheckKind());
		}
		if (StringUtils.hasText(contract.getProductKind())) {
			contractVo.setProductKind(contract.getProductKind());
		}
		if (StringUtils.hasText(contract.getSignOfficer())) {
			contractVo.setSignOfficer(contract.getSignOfficer());
		}
		if (StringUtils.hasText(contract.getRepairOfficer())) {
			contractVo.setRepairOfficer(contract.getRepairOfficer());
		}
		if (StringUtils.hasText(contract.getQuotationOfficer())) {
			contractVo.setQuotationOfficer(contract.getQuotationOfficer());
		}
		if (StringUtils.hasText(contract.getOperatDepartment())) {
			contractVo.setOperatDepartment(contract.getOperatDepartment());
		}
		if (StringUtils.hasText(contract.getOperator())) {
			contractVo.setOperator(contract.getOperator());
		}
		if (contract.getOperatDate() != null) {
			contractVo.setOperatDate(contract.getOperatDate());
		}
		if (StringUtils.hasText(contract.getMemo())) {
			contractVo.setMemo(contract.getMemo());
		}
		if (StringUtils.hasText(contract.getName())) {
			contractVo.setName(contract.getName());
		}
		if (StringUtils.hasText(contract.getProjectCode())) {
			contractVo.setProjectCode(contract.getProjectCode());
		}
		if (StringUtils.hasText(contract.getRepairCode())) {
			contractVo.setRepairCode(contract.getRepairCode());
		}
		contractVo.setRepairNumber(contract.getRepairNumber());
		if (StringUtils.hasText(contract.getRepairKind())) {
			contractVo.setRepairKind(contract.getRepairKind());
		}
		if (StringUtils.hasText(contract.getRepairKind())) {
			contractVo.setRepairKind(contract.getRepairKind());
		}
		if (contract.getRepairDate() != null) {
			contractVo.setRepairDate(contract.getRepairDate());
		}
		return contractVo;
	}

	@Override
	public Map<String, Object> newAddCount(Map<String, String> condition) {
		Map<String, Object> count=new HashMap<String, Object>();	
		long contractCount=0;
		long customerCount=0;
		long chanceCount=0;		
		contractCount=this.getNewContract(condition);
		chanceCount=this.getNewChance(condition);
		customerCount=this.getNewCustomer(condition);
		count.put("contractCount", contractCount);
		count.put("cusCount", customerCount);
		count.put("chanceCount", chanceCount);
		return count;
	}

	@Override
	public long getNewChance(Map<String, String> condition) {
		String userId = condition.get("userId");
		String superior = condition.get("superior");
		String areaId = condition.get("areaId");
		String sectionId = condition.get("sectionId");
		String chanceFilter=condition.get("chanceFilter");
		Date end=new Date();
		Date start=DataConverter.toMonthStartDate(end);
		long chanceCount=0;
		if(chanceFilter!=null){
			if(chanceFilter.equals("所有")){
				chanceCount=chanceDeliveryRepository.getAllNewChanceCount(start, end);
			}else if(chanceFilter.equals("本部门")){
				chanceCount=chanceDeliveryRepository.getNewChanceCount(superior, start, end);	
			}else if(chanceFilter.equals("本科室")){
				chanceCount=chanceDeliveryRepository.getSectionNewChanceCount(sectionId, start, end);
			}else if(chanceFilter.equals("本片区")){
				chanceCount=chanceDeliveryRepository.getAreaNewChanceCount(areaId, start, end);	
			}else if(chanceFilter.equals("本人")){
				chanceCount=chanceDeliveryRepository.getMyNewChanceCount(userId, start, end);
			}
		}
		
		return chanceCount;
	}

	@Override
	public long getNewContract(Map<String, String> condition) {
		Date end=new Date();
		Date start=DataConverter.toMonthStartDate(end);
		String userId = condition.get("userId");
		String superior = condition.get("superior");
		String sectionId = condition.get("sectionId");
		String areaName=condition.get("areaName");
		String cFilter=condition.get("cFilter");
		long contractCount=0;
		if(cFilter!=null){
			if(cFilter.equals("所有")){
				contractCount = contractRepository.getAllNewCCount(start, end);
			}else if(cFilter.equals("本部门")){
				contractCount = contractRepository.getSuperiorNewCCount(superior, start, end);
			}else if(cFilter.equals("本科室")){
				contractCount = contractRepository.getSectionNewCCount(superior, sectionId, start, end);
			}else if(cFilter.equals("本片区")){
				contractCount = contractRepository.getAreaNewCCount(superior, areaName, start, end);
			}else if(cFilter.equals("本人")){
				contractCount = contractRepository.getMyNewCCount(userId, start, end);
			}
		}
		return contractCount;
	}

	@Override
	public long getNewCustomer(Map<String, String> condition) {
		String userId = condition.get("userId");
		String superior = condition.get("superior");
		String sectionId = condition.get("sectionId");
		String areaId = condition.get("areaId");
		String customerFilter=condition.get("customerFilter");
		Date end=new Date();
		Date start=DataConverter.toMonthStartDate(end);
		long customerCount=0;
		if(customerFilter!=null){
			if(customerFilter.equals("所有")){
				customerCount = contractRepository.getAllNewCustomer(start, end);
			}else if(customerFilter.equals("本部门")){
				customerCount = contractRepository.getSuperiorNewCustomer(superior, start, end);
			}else if(customerFilter.equals("本科室")){
				customerCount = contractRepository.getSectionNewCustomer( sectionId, start, end);
			}else if(customerFilter.equals("本片区")){
				customerCount = contractRepository.getAreaNewCustomer(areaId, start, end);
			}else if(customerFilter.equals("本人")){
				customerCount = contractRepository.getMyNewCustomer(userId, start, end);
			}
		}	
		return customerCount;
	}
}
